<template>
  <el-form :model="skuInfo" :rules="skuFormRules" ref="skuForm" label-width="120px" class="sku-form">
    <el-form-item label="SPU名称">
      <span>{{spuInfo.spuName}}</span>
    </el-form-item>
    <el-form-item label="SKU名称" prop="skuName">
      <el-input v-model="skuInfo.skuName" placeholder="请输入SKU名称"></el-input>
    </el-form-item>
    <el-form-item label="价格(元)" prop="price">
      <el-input v-model="skuInfo.price" type="number"></el-input>
    </el-form-item>
    <el-form-item label="重量(千克)" prop="weight">
      <!-- <el-input-number v-model="skuInfo.weight" style="width:100%;" class="mx-4" :min="1" :max="100" controls-position="right" /> -->
      <el-input v-model="skuInfo.weight" :min="1" :max="100" type="number"></el-input>
    </el-form-item>
    <el-form-item label="规格描述" prop="skuDesc">
      <el-input v-model="skuInfo.skuDesc" placeholder="请输入规格描述" :rows="4" type="textarea" />
    </el-form-item>
    <el-form-item label="平台属性" prop="skuAttrValueList">
      <el-row :gutter="20">
        <el-col v-for="(attr,index) in attrList" :key="attr.id" :xs="24" :sm="12" :md="8" :lg="8">
          <el-form-item :label="attr.attrName">
            <el-select v-model="skuInfo.skuAttrValueList[index]" placeholder="请选择" @change="clearSkuAttrRule">
              <el-option v-for="attrValue in attr.attrValueList" :key="attrValue.id" :label="attrValue.valueName" :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`" />
            </el-select>
            <!-- <el-select v-model="skuInfo.skuAttrValueList[index]" placeholder="请选择">
              <el-option v-for="attrValue in attr.attrValueList" :key="attrValue.id" :label="attrValue.valueName" :value="{'attrId':attr.id,'attrName':attr.attrName,'valueId':attrValue.id,'valueName':attrValue.valueName}" />
            </el-select> -->
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="销售属性" prop="skuSaleAttrValueList">
      <el-form-item v-for="(saleAttr,index) in spuSaleAttrList" :key="saleAttr.id" :label="saleAttr.saleAttrName">
        <el-select v-model="skuInfo.skuSaleAttrValueList[index]" placeholder="请选择" @change="clearSaleAttrRule">
          <el-option v-for="saleAttrValue in saleAttr.spuSaleAttrValueList" :key="saleAttrValue.id" :label="saleAttrValue.saleAttrValueName" :value="saleAttr.id+':'+saleAttr.saleAttrName+':'+saleAttrValue.id+':'+saleAttrValue.saleAttrValueName" />

          <!-- <el-option v-for="saleAttrValue in saleAttr.spuSaleAttrValueList" :key="saleAttrValue.id" :label="saleAttrValue.saleAttrValueName" :value="{'saleAttrId':saleAttr.id,'saleAttrName':saleAttr.saleAttrName,'saleAttrValueId':saleAttrValue.id,'saleAttrValueName':saleAttrValue.saleAttrValueName}" /> -->
        </el-select>
      </el-form-item>
    </el-form-item>
    <el-form-item label="图片列表" prop="skuImageList">
      <el-table border :data="spuImageList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="80" align="center"></el-table-column>
        <el-table-column label="图片" align="center">
          <template v-slot="{row}">
            <el-image style="width: 100px; height: 100px" :src="row.imgUrl" />
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="imgName" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="{row}">
            <el-button type="primary" v-if="row.isDefault==='0'" @click="setDefaultImg(row)">设置为默认项</el-button>
            <el-button type="success" v-else :disabled="true">默认图片</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(skuForm)">保存</el-button>
      <el-button @click="emits('setShowStatus',ShowStatus.SPU_LIST)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
export default {
  name: 'SkuForm'
};
</script>
<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue';
import { reqGetSpuImageListData, reqGetSpuSaleAttrListData } from '@/api/product/spu';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import { reqGetAttrListData } from '@/api/product/attr';
import { useCategoryListStore } from '@/stores/categoryList';
import { ShowStatus } from '../types';
import { reqSaveSkuInfo } from '@/api/product/sku';
const emits = defineEmits(['setShowStatus']);
// 获取对应的store对象
const categoryStore = useCategoryListStore();
const props = defineProps(['spuInfo']);
const num = ref(1);

const spuImageList = ref([]);
const spuSaleAttrList = ref([]);
const attrList = ref([]);

const skuForm = ref<FormInstance>();
// 定义一个skuInfo对象 用来收集对应的数据
const skuInfo = reactive({
  spuId: 0,
  category3Id: 0,
  // spu名称
  skuName: '',
  // 价格
  price: 0,
  // 重量
  weight: '0',
  // 描述
  skuDesc: '',
  // 默认图片
  skuDefaultImg: '',
  // 平台属性
  skuAttrValueList: [],
  // 图片列表
  skuImageList: [],
  // 销售属性列表
  skuSaleAttrValueList: []
});

// 0. 对skuInfo中的数据做校验
const skuFormRules = reactive<FormRules>({
  skuName: [
    { required: true, message: '请输入SkuName', trigger: 'blur' },
    { min: 1, max: 10, message: '长度应该在1 to 10之间', trigger: 'blur' }
  ],
  skuDesc: [{ required: true, message: '请输入Sku描述', trigger: 'blur' }],
  price: [{ required: true, message: '请输入sku价格', trigger: 'blue' }],
  weight: [{ required: true, message: '请输入sku重量', trigger: 'blue' }],
  skuImageList: [
    {
      type: 'array',
      required: true,
      message: '请至少选择三张图片',
      trigger: 'change'
    }
  ],
  skuSaleAttrValueList: [
    {
      type: 'array',
      required: true,
      message: '请选择至少一个销售属性',
      trigger: 'change'
    }
  ],
  skuAttrValueList: [
    {
      type: 'array',
      required: true,
      message: '请选择至少一个平台属性',
      trigger: 'change'
    }
  ]
});

// 1. 组件挂载完毕之后 在onMounted当中一次性发送三次请求
onMounted(async () => {
  // Promise.all()  强调的是整体都成功了,整个结果才是成功 是响应回来的数据组成的数组
  // 如果有任何一个失败了,则最终结果就是失败
  // Promise.allSettled 与上面的参数一样  但是允许结果有失败项 个别失败不影响整体
  // Promise.race() race赛跑的意思 就是抢先机制 哪个最先成功结果 就是哪个
  let [resSpuImageList, resSpuSaleAttrList, resAttrList] = await Promise.allSettled([
    reqGetSpuImageListData(props.spuInfo.id),
    reqGetSpuSaleAttrListData(props.spuInfo.id),
    reqGetAttrListData({
      category1Id: categoryStore.category1Id as number,
      category2Id: categoryStore.category2Id as number,
      category3Id: categoryStore.category3Id as number
    })
  ]);

  // 由于Promise.allSettled允许有个别请求是失败的情况 但是某个失败并不影响其它的接口请求
  // 在使用服务器端响应回来的数据的时候，一定要进行判断
  if (resSpuImageList.status === 'fulfilled') {
    spuImageList.value = resSpuImageList.value.map(item => {
      return {
        ...item,
        isDefault: '0' // 给所有的图片先添加一个默认的'0' 值  表示当前非默认项  1表示默认图片
      };
    });
  }
  if (resSpuSaleAttrList.status === 'fulfilled') {
    spuSaleAttrList.value = resSpuSaleAttrList.value;
  }
  if (resAttrList.status === 'fulfilled') {
    attrList.value = resAttrList.value;
  }

  // console.log('ss', resSpuImageList, resSpuSaleAttrList, resAttrList);
});

// 2. 设置默认图片
const setDefaultImg = row => {
  // 2.1 要将其它的先设置为非默认
  spuImageList.value.forEach(item => {
    item.isDefault = '0';
  });
  // 2.2 将当前被单击的设置为默认项
  row.isDefault = '1';

  // 2.3 要将当前设置的设置图片链接获取下来 ，保存一下
  skuInfo.skuDefaultImg = row.imgUrl;
};

// 3. 收集选中的图片
const handleSelectionChange = val => {
  // console.log('vv',val)
  skuInfo.skuImageList = val;
};

// 4. 添加skuInfo
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // 4.3 判断一下选择的那些图片当中，是否有默认图片
      let flag = skuInfo.skuImageList.every(item => item.isDefault === '0');
      if (flag) {
        ElMessage.warning('请在选择的图片中设置一个默认图片');
        return;
      }
      // 发送请求
      // 4.1 添加对应的spuId和category3Id
      skuInfo.spuId = props.spuInfo.id;
      skuInfo.category3Id = categoryStore.category3Id as number;

      // 4.2 处理一下那两个数组  收集数据的时候是以字符串格式存储在了数组当中
      // 但是发送给服务器的时候，要以数组中对象的格式 来发送给服务器
      skuInfo.skuAttrValueList = skuInfo.skuAttrValueList.filter(Boolean).map(item => {
        // console.log('cc',item)
        const [attrId, attrName, valueId, valueName] = item.split(':');
        return {
          attrId,
          attrName,
          valueId,
          valueName
        };
      });

      skuInfo.skuSaleAttrValueList = skuInfo.skuSaleAttrValueList.filter(Boolean).map(item => {
        const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] = item.split(':');
        return {
          saleAttrId,
          saleAttrName,
          saleAttrValueId,
          saleAttrValueName
        };
      });

      
      // 4.4 发送请求 实现添加
      await reqSaveSkuInfo(skuInfo);

      // 4.5 提示
      ElMessage.success('添加skuInfo成功了...');

      // 4.6 跳转到列表页面
      emits('setShowStatus', ShowStatus.SPU_LIST);
    } else {
      console.log('error submit!', fields);
    }
  });
};

// 5. 清空平台属性规则
const clearSkuAttrRule = () => {
  skuForm.value?.clearValidate(['skuAttrValueList']);
};

// 6. 清空销售属性的提示
const clearSaleAttrRule = () => {
  skuForm.value?.clearValidate(['skuSaleAttrValueList']);
};
</script>
<style lang="scss" scoped>
.sku-form {
  .el-form-item {
    margin-bottom: 18px;
  }
}
</style>